package com.gitee.feizns.quickstart.jackson.deserializer;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;

/**
 * 重复数据删除列表反序列化程序
 * @author feizns
 * @since 2025/8/5
 */
public class DeduplicatingListDeserializer extends JsonDeserializer<List<Object>> implements ContextualDeserializer {


    private final JavaType elementType;

    public DeduplicatingListDeserializer() {
        this.elementType = null;
    }

    /**
     * 重复数据删除列表反序列化程序
     * @param contentType 内容类型
     */
    public DeduplicatingListDeserializer(JavaType contentType) {
        this.elementType = contentType;
    }

    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext cnt, BeanProperty property) {
        JavaType collectionType = property.getType();
        return new DeduplicatingListDeserializer(collectionType.getContentType());
    }

    @Override
    public List<Object> deserialize(JsonParser p, DeserializationContext cnt) throws IOException {
        List<Object> list = cnt.readValue(p, cnt.getTypeFactory().constructCollectionType(List.class, elementType));
        return list == null ? null : new ArrayList<>(new LinkedHashSet<>(list));
    }

}
